<?php
namespace Home\Controller;

use Utuo\DistributionShopForeground;

class DisShopCartController extends DistributionShopForeground {
	
	protected $cart = null;
	
	public function _init() {
		//session('cart', null);
		layout('disshop');
		$this->setModelName("DistributionShop");
		$this->setModelControllerName("DisShop");
		$this->cart = $this->getCart();
	}
	
	// 添加商品到购物车
	public function addItemAction() {
		$id = I("id", 0, "intval");
		$quantity =  I("quantity", 1, "intval") and $quantity===0 and $quantity = 1;
		$attrs = I("attrs");
		$d = D("My/DistributionShopGoods", "Model");
		$product = $d->getUserSubmitGoods($id, $attrs) or $this->ajaxError($d->getError());
		$result = $this->cart->addItem($product, $quantity);
		$result ? $this->ajaxSuccess("添加成功!") :  $this->ajaxError("添加失败!");
	}
	
	// 显示购物车
	public function showCartAction() {
		$d = D("My/DistributionShopGoods", "Model");
		$items = $this->cart->getItems();
		foreach ($items as &$v) {
			/*处理显示属性可看*/
			foreach ($v['items'] as &$v0) {
				$tmpAttrs = array();
				$attrInfo = $v0['attrs']; // 属性信息
				foreach ($attrInfo as $k1 => $v1) {
					$tmpAttrs[$k1] = array_pop($v1);
				}
				$v0['attrs'] = $tmpAttrs;
			}
		}
		$this->assign('cartItems', $items);
		$this->setPageTitle('我的购物车');
		$this->display("{$this->modelControllerName}/cart");
	}
	
	// 移除购物车商品
	public function removeItemAction() {
		$productId = I('productId', 0);
		$businessId = I('businessId', 0);
		if($this->cart->removeItem($productId, $businessId)) {
			$this->ajaxSuccess("移除成功");
		}
		$this->ajaxSuccess("移除失败");
	}
	
	// 更新数量
	public function updateQuantityAction() {
		$productId = I('productId', 0, 'intval');
		$businessId = I('businessId', 0);
		$quantity = I('quantity', 0, 'intval');
		false !== $this->cart->updateItem($productId, $businessId, array('quantity' => $quantity)) ? $this->ajaxSuccess("修改成功") : $this->ajaxError("修改失败");
	}
	
	// 获得购物车商品数量
	public function getCountAction() {
		echo $this->cart->getCount();
	}
	
	// 获得购物车
	protected function getCart() {
		return \Utuo\DisCart::getCart ($this->uid, $this->sid );
	}
	
}